package com.michael.study.jetpack.module.coroutines

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.michael.study.jetpack.R
import com.michael.study.jetpack.bean.User
import com.michael.study.jetpack.db.DBRoom
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

class CoroutinesActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_coroutines)
        testFlow2()
    }

    fun testFlow() {
        GlobalScope.launch {
            flow<Int> {
                for (i in 1..5) {
                    emit(i)
                }
            }.collect {
                Log.d("lgq", "testFlow: " + it)
            }
        }
    }


    fun testFlow2() {
        GlobalScope.launch {
            flowOf(1,2,3,4,5)
                .onEach {
                    Log.d("lgq", "onEach: " + it)

                }.collect {
                    Log.d("lgq", "testFlow2: " + it)

                }
        }
    }


    fun testCoroutinesRoom() {
        var dao = DBRoom.getDataBase(this).getUserDao()
        GlobalScope.launch {
            var user = User("123", "male")
            val id = dao.insert(user)
            for (user in dao.queryAllUsers()) {
                Log.d("lgq", "onClick: ${user.toString()}")
            }
            user = dao.queryUser(id)
            Log.d("lgq", "onClick: ${user.toString()}")
        }
    }
}